<template>
	<view class="login-con">
		<u-navbar back-text="返回" title=""></u-navbar>
		<view class="title">手机号码登录</view>
		<view class="form">
			<view class="">
				<u-field
					type="number"
					v-model="form.mobile"
					label="手机号"
					placeholder="请填写手机号"
					class="phone"
				>
				</u-field>
			</view>
			<view class="">
				<u-field
					type="number"
					v-model="form.code"
					label="验证码"
					placeholder="请填写验证码"
					class="phone"
				>
					<u-button class="send-code" size="mini" slot="right" type="success" @click="getCode">{{codeText}}</u-button>
				</u-field>
				<u-verification-code :seconds="10" ref="uCode" @change="codeChange"></u-verification-code>
			</view>
		</view>
		<view class="btn">
			<u-button shape="circle" type="primary" class="login" :disabled="disabled" @click="codeLogin">登录</u-button>
			<view class="quick" @click="quickLogin">手机号一键登录</view>
			<view class="quick" @click="passwordLogin" v-if="password_login">密码登录</view>
		</view>
		<view class="wx-login" v-if="wxLogin">
			<view class="other">
				<view class="line"></view>
				<text>其他登录方式</text>
				<view class="line"></view>
			</view>
			<image src="../../static/login_wx.jpg" mode="" @click="wxAuthLogin"></image>
		</view>
	</view>
</template>

<script>
	// #ifdef APP-PLUS
	const jv = uni.requireNativePlugin('JG-JVerification')
	// #endif
	import login from '../../api/login.js'
	import { sendCode, userCodeLogin, wxLogin, getLoginWX } from '../../api/globalApi.js'
	export default {
		data() {
			return {
				form: {
					// mobile: '15806084632',
					mobile: '',
					code: ''
				},
				codeText: '',
				disabled: false,
				curRoute: '',
				wxLogin: true, // 是否开启微信登录
				password_login: true  // 是否开启密码登录
			}
		},
		onLoad() {
			let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
			let curRoute = routes[routes.length - 2].route // 获取当前页面路由
			this.curRoute = curRoute
			console.log(this.curRoute)
			this._getLoginWX()
		},
		methods: {
			async _getLoginWX() {
				const res = await getLoginWX()
				console.log(res)
				this.wxLogin = res.data.data.login_types.wx_login == 0 ? false : true
				this.password_login = res.data.data.login_types.password_login == 0 ? false : true
				console.log(this.password_login)
			},
			codeChange(text) {
				this.codeText = text;
			},
			getCode() {
				if (!this.form.mobile) return this.$u.toast('请输入手机号')
				if (!this.$utils.regTel(this.form.mobile)) return this.$u.toast('请输入正确的手机号')
				if(this.$refs.uCode.canGetCode) {
					// 模拟向后端请求验证码
					uni.showLoading({
						title: '正在获取验证码'
					})
					setTimeout(async () => {
						uni.hideLoading();
						// 通知验证码组件内部开始倒计时
						this.$refs.uCode.start();
						const res = await sendCode({mobile: this.form.mobile-0,channel: 1})
						console.log(res)
						// jv.setTimeWithConfig(7000); // 设置前后两次获取验证码的时间间隔。
						// jv.getCode({
						//     phoneNumber :  this.form.mobile + '',
						// 	signID: '15706',
						// 	templateID: '185157'
						// },result => {
						// 	console.log(result)
						// },event => {
						// 	console.log(event)
						// })
					}, 1000);
				}else {
					this.$u.toast('倒计时结束后再发送');
				}
			},
			async codeLogin() {
				if (!this.form.code) return this.$u.toast('请输入验证码')
				const res = await userCodeLogin({mobile: this.form.mobile-0,code: this.form.code-0})
				if (res.data.code === 103) return this.$u.toast('验证码')
				console.log(res)
				console.log(res.data.data.token)
				// #ifdef APP-PLUS
				this.$IM.login({userId:res.data.data.member.id + '',userSig:res.data.data.sin},(ret)=>{
					console.log('IM登录',ret);
				});
				// #endif
				uni.setStorageSync('user',res.data.data)
				uni.setStorageSync('token',res.data.data.token)
				uni.setStorageSync('isLogin', true)
				uni.setStorageSync('isRefresh', true)
				if (this.curRoute.includes('phone')) {
					console.log('789789')
					uni.switchTab({url: '/pages/user/user'})
				} else {
					console.log('123456')
					uni.navigateBack()
				}
			},
			quickLogin() {
				login()
			},
			passwordLogin() {
				console.log('点击了密码登录')
				uni.navigateTo({url: '/pages/login/loginPassword'})
			},
			// 微信登录
			wxAuthLogin() {
				uni.getProvider({
					service: 'oauth',
					success: (res)=> {
						console.log(res.provider);
						//支持微信、qq和微博等
						if (~res.provider.indexOf('weixin')) {
							console.log('weixin123')
							uni.login({
								provider: 'weixin',
								success: (loginRes)=> {
									console.log('-------获取openid(unionid)-----');
									console.log(loginRes);
									console.log(JSON.stringify(loginRes));
									// let pages = getCurrentPages()
									// let page = pages[pages.length - 2].route
									// // 哪里进来的登录成功后返回哪里
									// console.log(page)
									// 获取用户信息
									uni.getUserInfo({
										provider: 'weixin',
										success: async (infoRes)=> {
											uni.showLoading({title:'加载中'})
											console.log('-------获取微信用户所有-----');
											// console.log(JSON.stringify(infoRes.userInfo));
											console.log(infoRes.userInfo)
											uni.setStorageSync('userInfo', infoRes.userInfo)
											// let pages = getCurrentPages()
											// let page = pages[pages.length - 1].route
											// // 哪里进来的登录成功后返回哪里
											// console.log(page)
											// const result = await wxLogin({openid: infoRes.userInfo.openId})
											// console.log(result) 
											let baseUrl = ''
											if (process.env.NODE_ENV === "development") {
												baseUrl = 'https://api.arapp.net'
											} else {
												baseUrl = 'https://api.arapp.net'
											}
											uni.request({
												url: baseUrl + '/client/visitor/auth',
												data: {openid: infoRes.userInfo.openId,unionid: infoRes.userInfo.unionId},
												success: (res) => {
													console.log(res.data)
													if (res.data.code === 207) {
														uni.showToast({title: res.data.message, icon: 'none'})
														uni.navigateTo({url: '/pages/setting/bind-phone'})
													} else if (res.data.code === 0) {
														// #ifdef APP-PLUS
														this.$IM.login({userId:res.data.data.member.id + '',userSig:res.data.data.sin},(ret)=>{
															console.log('IM登录',ret);
														});
														// #endif
														uni.setStorageSync('user',res.data.data)
														uni.setStorageSync('token',res.data.data.token)
														uni.setStorageSync('isLogin', true)
														uni.setStorageSync('isRefresh', true)
														let routes = getCurrentPages()
														let curRoute = routes[routes.length - 1].route
														console.log(curRoute)
														if (curRoute==="pages/login/login") {
															uni.switchTab({url: '/pages/user/user'})
														} else {
															uni.navigateBack()
														}
													} else {
														uni.showToast({title: res.data.message, icon: 'none'})
													}
													// this.$IM.login({userId:res.data.data.member.id + '',userSig:res.data.data.sin})
													// uni.setStorageSync('user',res.data.data)
													// uni.setStorage({
													// 	key: 'token', 
													// 	data: res.data.data.token, 
													// 	success: ()=> {
													// 		console.log('token设置登录成功')
													// 		// uni.redirectTo({url: '/pages/index/index2.vue'})
													// 		resolve('登录成功' + res.data.data.token)
													// 		let routes = getCurrentPages()
													// 		let curRoute = routes[routes.length - 1].route
													// 		console.log(curRoute)
													// 		if (curRoute==="pages/user/user") {
													// 			// uni.setStorageSync({
													// 			//     key: 'isLogin',
													// 			//     data: true,
													// 			//     success: ()=> {
													// 			// 		console.log('登录成功')
													// 			// 		uni.startPullDownRefresh()
													// 			//     }
													// 			// })
													// 			uni.setStorageSync('isLogin', true)
													// 			uni.setStorageSync('isRefresh', true)
													// 			uni.startPullDownRefresh()
													// 		}
															
													// 	}
													// })
												},
												fail: (err) => {
													console.log(err)
												},
												complete: () => {
													uni.hideLoading()
												}
											})
											// setTimeout(() => {
											// 	// uni.switchTab({url: `/${page}`})
											// 	uni.navigateBack()
											// }, 500)
											// uni.setStorage({
											//     key: 'userInfo',
											//     data: infoRes.userInfo,
											//     success: ()=> {
											//         console.log(infoRes.userInfo);
											//     }
											// });
											// console.log(this.superiorId+"-"+this.agent)
											// let data = {
											// 	img: infoRes.userInfo.avatarUrl,
											// 	nickName: infoRes.userInfo.nickName,
											// 	openId: infoRes.userInfo.openId,
											// 	superiorId: this.superiorId,
											// 	agent:this.agent,
											// 	city: infoRes.userInfo.city,
											// }
											// const result = await wxLogin(data)
											// console.log(result)
											
											// this.$store.dispatch('getAuthorization', result.data.data.tokenHead + result.data.data.token)
											// uni.setStorage({
											//     key: 'token',
											//     data: result.data.data.tokenHead + result.data.data.token,
											//     success: ()=> {
											//         console.log('设置success');
											//     }
											// });
											// uni.request({
											// 	url: 'http://118.31.1.12:8085/sso/info',
											// 	method: 'GET', // 不传默认'GET'请求
											// 	header: {'Authorization': result.data.data.tokenHead + result.data.data.token},
											// 	success: (res) => {
											// 		//设置缓存
											// 		uni.setStorage({
											// 			key:'userInfoObj',
											// 			data:res.data.data,
											// 			success: () => {
											// 				console.log(res.data.data)
											// 			}
											// 		})
											// 		console.log(res)
											// 		this.$store.dispatch('getMemberId', res.data.data.id)
											// 		this.$store.dispatch('getUserInfoObj', res.data.data)
											// 	}
											// })
											// uni.reLaunch({url: `../index/index`})
										}
									});
								}
							});
						}
					}
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.title {
		padding: 20% 0 0 10%;
		font-size: 40rpx;
		font-weight: bold;
	}
	.form {
		margin: 20% 10% 0;
	}
	.phone {
		padding-left: 0 !important;
		padding-right: 0 !important;
	}
	.btn {
		margin: 10% 10% 0;
		
	}
	.login {
		// background-image: linear-gradient(to, right, #5f86fd,#506ffe,#3d55ff);
		background: #1b63d2;
		color: #fff !important;
		border-color: #1b63d2;
	}
	.quick {
		text-align: center;
		padding: 60rpx 0 0 0;
	}
	.wx-login {
		color: #666;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		margin-top: 100rpx;
		.other {
			display: flex;
			align-items: center;
			text {
				padding: 0 30rpx;
			}
			.line {
				width: 180rpx;
				height: 1px;
				background-color: #e5e5e5;
				display: flex;
			}
		}
		image {
			width: 80rpx;
			height: 80rpx;
			margin-top: 20rpx;
		}
	}
	.send-code {
		background: #1b63d2;
	}
</style>
